package vip.xiaonuo.core.utils;

import org.apache.commons.lang3.time.DateFormatUtils;
import vip.xiaonuo.core.constant.Constants;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * 时间工具类
 *
 * @author: tyc
 */
public class DateUtils {
    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYY = "yyyy";

    public static String YYYYMM = "yyyyMM";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String EXCEL_DATE_1 = "yyyy/MM/dd";

    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public static SimpleDateFormat sdfYm = new SimpleDateFormat("yyyy-MM");

    public static SimpleDateFormat sdfYmNum = new SimpleDateFormat("yyyyMM");

    // Date类型转Calendar类型
    public static Calendar dataToCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    public static String getSmsMsg() {
        String code;
        Random random = new Random();
        code = (random.nextInt(9999 - 1000 + 1) + 1000) + "";
        return code;
    }

    // 时间格式规范化
    public static String dateFormat(String obj) throws ParseException {
        Date parse = sdf.parse(obj);
        String s = dateTime(parse);
        return s;
    }

    // 特殊事件格式规范化
    public static String specialDateFormatEndToM(Date obj) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(obj);
        String result = calendar.get(Calendar.YEAR) + "." + (calendar.get(Calendar.MONTH) + 1);
        return result;
    }

    public static String specialDateFormat(Date obj) throws ParseException {
        if (obj == null) {
            return Constants.EMPTY;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(obj);
        String result = calendar.get(Calendar.YEAR) + "." + (calendar.get(Calendar.MONTH) + 1) + "." + calendar.get(Calendar.DAY_OF_MONTH);
        return result;
    }

    // 时间格式规范化
    public static String dateFormat(String pattern, String obj) throws ParseException {
        Date date = DateUtils.dateTime(pattern, obj);
        String s = DateUtils.parseDateToStr(pattern, date);
        return s;
    }


    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static final Date dateTimeLenient(final String format, final String ts) {
        try {
            DateFormat formatter = new SimpleDateFormat(format);
            formatter.setLenient(false);
            return formatter.parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 获取一天的开始时间（如：2015-11-3 00:00:00.000）
     *
     * @param date 日期
     * @return
     */
    public static Date getOfDayFirst(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取一天的最后时间（如：2015-11-3 23:59:59.999）
     *
     * @param date 日期
     * @return
     */
    public static Date getOfDayLast(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * @param @param  date1
     * @param @param  date2
     * @param @return
     * @return int
     * @Description: 计算2个日期相差几天
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) // 同一年
        {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) // 闰年
                {
                    timeDistance += 366;
                } else // 不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2 - day1);
        } else // 不同年
        {
            return day2 - day1;
        }
    }

    /**
     * 比较2个时间前后 参数Date型
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return Boolean
     */
    public static Boolean compare(Date start, Date end) {
        if (start == null || end == null) {
            return Boolean.FALSE;
        }
        // 比较时间
        if (start.after(end)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 比较2个时间前后 参数String型(yyyy-MM-dd)
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return Boolean
     * @throws ParseException
     */
    public static Boolean compare(String start, String end) throws ParseException {
        if (StringUtils.isBlank(start) || StringUtils.isBlank(end)) {
            return Boolean.FALSE;
        }
        // 比较时间
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 比较2个时间前后 参数String型(yyyy-MM)
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return Boolean
     * @throws ParseException
     */
    public static Boolean compareYM(String start, String end) throws ParseException {
        if (StringUtils.isBlank(start) || StringUtils.isBlank(end)) {
            return Boolean.FALSE;
        }
        // 比较时间
        Date startDate = sdfYm.parse(start);
        Date endDate = sdfYm.parse(end);
        if (startDate.after(endDate)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 比较2个时间前后 参数Date型
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return Boolean
     * @throws ParseException
     */
    public static Boolean compareYM(Date start, Date end) throws ParseException {
        // 比较时间
        Date startDate = sdfYm.parse(sdfYm.format(start));
        Date endDate = sdfYm.parse(sdfYm.format(end));
        if (startDate.after(endDate)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public static int differentMonths(Date date1, Date date2) {
        if (date1 != null || date2 != null) {
            String num1 = sdfYmNum.format(date1);
            String num2 = sdfYmNum.format(date2);
            return Math.abs(Integer.valueOf(num1) - Integer.valueOf(num2));
        }
        return 0;
    }
}
